const Admin = require('../models/admin');
const {Op} = require('sequelize')
const jsonwebtoken = require('jsonwebtoken')
const {secret} = require('../config/index')

class AdminsCtl{
  //创建管理员
  async create(ctx){
    //校验请求体的name位字符串类型并且是必选的
    ctx.verifyParams({
      username:{ type:'string',required:true },
      password:{type:'string',required:true },
    })
    //获取请求体中的用户名
    const {username} = ctx.request.body
    //findOne返回符合条件的第一个用户
    const repeatedAdmin = await Admin.findOne({
      where:{
          username:username
      }
    });
    //如果有重复用户返回409状态码代表冲突
    if(repeatedAdmin){
      ctx.throw(409,"用户名已被占用");
    }
    await Admin.create({
      username:username,
      password:ctx.request.body.password
    })
    ctx.body = {
      status:200,
      msg:'注册成功'
    };
  }
   //修改密码
  async updatePassword(ctx){
    const {password} = ctx.request.body;
      await Admin.update({
        password:password
      },{
        where:{
            admin_id:ctx.state.user.admin_id,
  
        }
      })
      ctx.body = {
        status:200,
        msg:'修改成功'
      }
  }
  //删除管理员
  async delete(ctx){
    const admin = await Admin.findOne({
      where:{
        admin_id:ctx.params.id
      }
    });
    if(!admin){ctx.throw(404,'管理员不存在')}
    await admin.destroy();
    ctx.status = 204
  }
  //登录
  async login(ctx){
    ctx.verifyParams({
      username:{type:'string',required:true},
      password:{type:'string',required:true},
    });
    //登录有两种情况：用户名不存在或密码错误，登录失败；登录成功
    //查找符合条件的第一个用户
    const admin = await Admin.findOne({
      where:{
        [Op.and]:{
          username:ctx.request.body.username,
          password:ctx.request.body.password
        }
      }
    });
    if(!admin){ctx.throw(401,'用户名或密码不正确！');}
    //获取id和username
    const {admin_id,username} = admin;
    const token = jsonwebtoken.sign({admin_id,username},secret,{expiresIn:'1d'});
    ctx.body = {
      status:200,
      data:{
        token,
        admin
      }
    };
  }
}
module.exports = new AdminsCtl();